from datetime import datetime
from spider.user_spider import user_blog_list
from dateutil.relativedelta import relativedelta
from domain.WeiboInfoDB import WeiboInfoDB

from database.weibo import insert_weibo, select_weibo_id, update_weibo
from database.common import conn

def get_user_weibo_and_store(user_id):
    # 拿到博客列表信息
    # 当前时间
    now = datetime.now()
    one_month_ago = now - relativedelta(months=1)
    # 只保留日期部分
    start_date = one_month_ago.date()
    blog_list = user_blog_list(user_id, start_date)
    for obj in blog_list:
        blog_class = WeiboInfoDB(**obj, user_id=user_id)
        weibo_id_result = select_weibo_id(blog_class.weibo_id)
        if weibo_id_result == None:
            print(f"插入新的微博:{blog_class.weibo_id}")
            insert_weibo(blog_class)
        else:
            print(f"更新旧的微博:{blog_class.weibo_id}")
            update_weibo(blog_class)
    conn.commit()
    
    print(f"用户{user_id}微博信息存储完成")

